import React, { JSX } from 'react';
import { NulDialog, NulCommonOperations, NulFormItem } from '../../components/NulDialog';
import '@fontsource/open-sans';
import { FormControl, MenuItem, Select, TextField } from '@mui/material';
import { useAppDispatch } from '../../actions/hook';
import { createNewCustomer } from '../../actions/CustomerManagement';

interface CreateCustomerProps {
  open: boolean;
  onClose: () => void;
}

function CreateCustomer(props: CreateCustomerProps): JSX.Element {
  const { open, onClose } = props;

  const [name, setName] = React.useState<string>('');
  const [type, setType] = React.useState<'wholesale' | 'retail'>('wholesale');
  const [phone, setPhone] = React.useState<string>('');
  const [address, setAddress] = React.useState<string>('');
  const [notes, setNotes] = React.useState<string>('');

  const dispatch = useAppDispatch();

  const clear = () => {
    setName('');
    setType('wholesale');
    setPhone('');
    setNotes('');
    setAddress('');
  }

  const onCreateClicked = () => {
    dispatch(createNewCustomer({ name, type, phone, address, notes }));
    onClose();
    clear();
  };

  return (
    <NulDialog
      open={open}
      onClose={onClose}
      title='Create New Customer'
      operations={
        <NulCommonOperations
          onPositiveClicked={onCreateClicked}
          onNegativeClicked={onClose}
          positiveText='Create'
        />
      }
    >
      <NulFormItem hint='Name' component={
        <TextField placeholder='Name' fullWidth={true} size='small' value={name} onChange={(event) => { setName(event.target.value); }} />
      } />
      <NulFormItem hint='Type' component={
        <FormControl fullWidth size='small'>
          <Select
            labelId="type-select-label"
            id="type-select"
            value={type}
            placeholder="Type"
            onChange={(event) => {
              if (event.target.value === 'wholesale' || event.target.value === 'retail')
                setType(event.target.value);
            }}
          >
            <MenuItem value={'wholesale'}>Wholesale</MenuItem>
            <MenuItem value={'retail'}>Retail</MenuItem>
          </Select>
        </FormControl>
      } />
      <NulFormItem hint='Phone' component={
        <TextField placeholder='Phone Number' fullWidth={true} size='small' value={phone} onChange={(event) => { setPhone(event.target.value); }} />
      } />
      <NulFormItem hint='Address' component={
        <TextField placeholder='Address' fullWidth={true} size='small' value={address} onChange={(event) => { setAddress(event.target.value); }} />
      } />
      <NulFormItem necessary={false} hint='Notes' component={
        <TextField placeholder='Notes' fullWidth={true} size='small' value={notes} onChange={(event) => { setNotes(event.target.value); }} />
      } />
    </NulDialog>
  );
}

export { CreateCustomer };